#!/usr/bin/env python
#-*- coding: utf-8 -*-

# @autor: Elísio Gonçalves Gomes Ribeiro
# @curso: Engenharia Informática 3ºano nº4708
# @subject: Estrutura de Dados e Algoritmo
# @@version: 1.0.0 2012/2013
# @google-code: https://code.google.com/p/eda12134708

###############################################################################
#
#
#

#------------------------------------------------------------------------------

import sys
from d_gen import DataGen
from algo import *
import IFace as ifc

#variables ------------------------------------------------------------------------------
dg = DataGen()
keys = dg.el_Times.keys()
choice = ''
#------------------------------------------------------------------------------




#show firsts options on screen to read data from file or generate lists
def on_ChooseDataOrigin():
    """show inicial screen options
    """
    global choice
    print '#########################################################'
    print """    Calculo de Tempo de Execução dos Algoritmos
    de Ordenação sobre uma Lista de Dados.
    Pode CARREGAR dados apartir de um ficheiro .txt ou .csv
    Pode GERAR listas com palavras e/ou numeros aleatórios
    """
    while(choice not in ['F', 'R']):
        ifc.pMenu_Data()
        choice = ifc.readvalues('c')
        
        if (choice == 'X'):
            break
        elif (choice in ['F', 'R']):
            try:
                on_ChooseFiles_Lists()
            except : raise
        pass
    pass
    

def on_ChooseFiles_Lists():
    global choice
    if (choice == 'F'):
        print ' insert the file name including the extension'
        choice = raw_input('FILE NAME: ')        
        try:
            options = dg.load_from_file(choice)
        except:
            print '\nERROR, File does not exists\n'
        else:
            __process_files(options)
        pass
    elif (choice == 'R'):
        __process_lists()
        onChooseMenu_ops()
    pass
    

def onChooseMenu_ops():
    global choice
    
    while((choice not in keys) or (choice == 'X')):         
        print '\n ## Algoritms To Run ##'
        ifc.pMenu_details()
        choice = ifc.readvalues('c')
        
        if (choice == 'X'):
            break
        elif (choice == 'D'):
            __show_details(keys[0], dg.el_Times[keys[0]])
            __show_details(keys[1], dg.el_Times[keys[1]])
            __show_details(keys[2], dg.el_Times[keys[2]])
            __show_details(keys[3], dg.el_Times[keys[3]])
            __show_details(keys[4], dg.el_Times[keys[4]])
        elif (choice == 'R'):
            processingAlgos(keys[0])
            processingAlgos(keys[1])
            processingAlgos(keys[2])
            processingAlgos(keys[3])
            processingAlgos(keys[4])
            choice = 'X'
        elif (choice == 'G'):
            print '\n   ## Information on Graphs ##'
            ifc.pMenu_graph()
            choice = ifc.readvalues('c')
            if (choice == '1'):
                choice = dg.draw_graph()
                print ' File Saved: '+choice+'\n'
            elif (choice == '2'):
                while(choice != 'X'):
                    print '\n   ## Algoritms to Draw ##'
                    ifc.pMenu_algo(keys)
                    choice = ifc.readvalues('c')
                    draw_graphs()
                pass
            pass
        elif (choice == 'S'):
            dg.save_el_times()
        elif (choice in keys):
            processingAlgos()
            choice = 'X'
        pass
    pass
    

def processingAlgos(rall=None):
    global choice
    if (dg.iList != None):
        print ' ORDERING . . .  . . .'
        data = [v for v in dg.iList]
        if(rall != None): choice = rall
        if (choice == keys[0]):
            algo = heap.HeapSort()
            dg.run_test(choice, lambda: algo.heap_Sort(data))
            
        elif (choice == keys[1]):
            algo = insertion.InsertionSort()
            dg.run_test(choice, lambda: algo.insertion_Sort(data))
            
        elif (choice == keys[2]):
            algo = quick.QuickSort()
            if (len(data) > 990):sys.setrecursionlimit(len(data)+1500)
            dg.run_test(choice, lambda: algo.quick_Sort(data, 0, len(data)-1))
            
        elif (choice == keys[3]):
            algo = merge.MergeSort()
            dg.run_test(choice, lambda: algo.merge_Sort(data, 0, len(data)-1))
        else:
            algo = bubble.BubbleSort()
            dg.run_test(choice, lambda: algo.bubble_Sort(data))
        pass
        print ' DONE!\n'
        dg.save_stats()
    pass
    

def __process_files(options):
    global choice
    while(choice !=''):
        print "\n    Ordering by:"
        k = 0
        for col in options:
            k+=1
            print "    %d\t %s" %(k, col)
        pass
        choice = ifc.readvalues('c')
        if (choice == 'X'): break
        try:
            choice = int(choice)
            if (choice > 0 and choice <= k):
                choice = options[choice-1]
                dg.iList = dg.get_read_content()[choice]
                dg.lsize = len(dg.iList)
                choice = raw_input(' Number of Test to Run: ')
                dg.rep_test = int(choice)
            pass
        except: 
            print '\nERRO, opção errada!'
        else:
            onChooseMenu_ops()
        pass
    pass
    

def __process_lists():
    global choice
    while(choice not in ['A', 'N']):            
        ifc.pMenu_Str_Nrs()
        choice = ifc.readvalues('c')
        if (choice == 'X'): break
        try:
            if (choice == 'A'):
                print "\
                Enter values separated by a SPACE chacater\
                'list_size'  'test_execution'\n\
                "
                __conv_read_data()
            elif (choice == 'N'):
                print "\
                Enter values separated by a SPACE chacater\
                'list_size' 'min_value' 'max_value' 'test_execution'\n\
                "
                __conv_read_data()
            else: raise            
        except: 
            print '\nERRO, opção errada!\n'
        else:
            return True
        pass
    pass
    

def __conv_read_data():
    choice = raw_input('ENTER VALUES: ')
    try:
        r_values = choice.split()
        r_values = [int(v) for v in r_values]
        argn = len(r_values)
        if (argn == 4):
            dg.lsize = r_values[0]
            dg.min_v = r_values[1]
            dg.max_v = r_values[2]
            dg.rep_test = r_values[3]
            dg.gen_numbers()
        elif (argn == 2):
            dg.lsize = r_values[0]
            dg.rep_test = r_values[1]
            dg.gen_strings()
        else:
            raise
        pass
    except: raise
    

def __show_details(algo, dt):
    
    print ' ',algo
    if (len(dt) == 0):
        print '\tNone'
    else:
        for val in dt.keys():
            print "\tList of %d elements" % val
        pass
    pass
    

def draw_graphs():
    global choice
    if ((choice in keys) and (len(dg.el_Times[choice]) > 0)):
        
        if (choice == keys[0]):
            choice = dg.draw_graph_algo(choice, dg.el_Times[choice])
        elif (choice == keys[1]):
            choice = dg.draw_graph_algo(choice, dg.el_Times[choice])
        elif (choice == keys[2]):
            choice = dg.draw_graph_algo(choice, dg.el_Times[choice])
        elif (choice == keys[3]):
            choice = dg.draw_graph_algo(choice, dg.el_Times[choice])
        elif (choice == keys[4]):
            choice = dg.draw_graph_algo(choice, dg.el_Times[choice])
        pass
        print '### File Saved: '+choice
    pass
    


###############################################################################
###############################################################################

if __name__== '__main__':

    on_ChooseDataOrigin()
